﻿using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Account;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Account
{
    public class AddAccountHandler : IRequestHandler<AddAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IMapper mapper;
        private readonly ILogger<AddAccountHandler> logger;

        public AddAccountHandler(IBaseRepository<AccountModel> accountRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<AccountRoleModel> accountroleRepo,
            IMapper mapper,
            ILogger<AddAccountHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountroleRepo = accountroleRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(AddAccountCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

                try
                {
                    var acc = accountRepo.GetAll().Where(x => !x.IsDeleted && x.Name == request.Name).ToList().FirstOrDefault();
                    if (acc != null)
                    {
                        res.Msg = "用户已存在";
                        res.Code = ApiEnum.Fail;
                        return await Task.FromResult(res);
                    }
                    var model = mapper.Map<AccountModel>(request);
                    model.Id = YitIdHelper.NextId();
                    int r = await accountRepo.CreateAsync(model);
                    int r1 = 0;
                    foreach (var item in request.RoleId)
                    {
                        var roles = await roleRepo.GetValue(item);
                        if (roles == null)
                        {
                            res.Msg = "无正确角色信息";
                            res.Code = ApiEnum.Fail;
                            return await Task.FromResult(res);
                        }
                        r += await accountroleRepo.CreateAsync(new AccountRoleModel { Id = YitIdHelper.NextId(), RoleId = item, AccountId = model.Id });
                    }
                    if (r + r1 > 0)
                    {
                        res.Data = r + r1;
                        res.Msg = "新增用户成功";
                        res.Code = ApiEnum.Success;
                    }
                    else
                    {
                        res.Data = r + r1;
                        res.Msg = "新增用户失败";
                        res.Code = ApiEnum.Fail;
                    }
                    logger.LogInformation($"新增用户{model.Name}成功");
                    return await Task.FromResult(res);
                }
                catch (Exception ex)
                {
                    logger.LogError("新增用户异常:" + ex.Message);
                    res.Msg = "新增用户异常:" + ex.Message;
                    res.Code = ApiEnum.Error;
                    return await Task.FromResult(res);
                }
        }
    }
}
